<?php
// +----------------------------------------------------------------------
// | @filename AuthLogic.php
// +----------------------------------------------------------------------
// | @author 落花轻舞问君愁 <mwcx1990@qq.com>
// +----------------------------------------------------------------------
// | @datetime 2021-10-26 17:45:08
// +----------------------------------------------------------------------
// | @Description
// +----------------------------------------------------------------------
namespace Addons\Backend\Logics;

use Addons\Backend\Repositories\AdminUserRepository;

use Illuminate\Support\Facades\Auth;


class AuthLogic extends BaseLogic
{
    protected $adminUserRepository;

    public function __construct(AdminUserRepository $adminUserRepository)
    {
        $this->adminUserRepository = $adminUserRepository;
    }

    /**
     * 登录
     * @param $username
     * @param $password
     * @return array
     */
    public function login($username, $password): array
    {
        $adminUser = $this->adminUserRepository->findByUsernameOrMobile($username);

        if (empty($adminUser)) {
            return $this->failed('账号不正确');
        }

        if ($adminUser['status'] == 2) {
            return $this->failed('账号已被禁用无法登陆,请联系管理员');
        }

        if ($token = Auth::guard('backend')->attempt(['username' => $username, 'password' => $password])) {
            return $this->respondWithToken($token);
        } elseif ($token = Auth::guard('backend')->attempt(['mobile' => $username, 'password' => $password])) {
            return $this->respondWithToken($token);
        }

        return $this->failed('密码不正确');
    }

    /**
     * 退出登录
     * @return array
     */
    public function logout(): array
    {
        Auth::guard('backend')->logout();
        return $this->success([], '退出登录成功');
    }


    /**
     * 刷新登录token（token未过期前刷新）
     * @return array
     */
    public function refresh(): array
    {
        return $this->respondWithToken(Auth::guard('backend')->refresh(), '刷新token成功');
    }

    /**
     * 响应token
     * @param $token
     * @param string $message
     * @return array
     */
    protected function respondWithToken($token, $message = '登录成功'): array
    {
        $expires = Auth::guard('backend')->factory()->getTTL() * 60 + time();
        $data['token'] = $token;
        $data['expires'] = date('Y-m-d H:i:s', $expires);
        return $this->success($data, $message);
    }
}
